# -*- coding: UTF-8 -*-
from django.shortcuts import render, HttpResponse
from django.http import StreamingHttpResponse, Http404
import json
from django.conf import settings
import os
import re

from django.utils.http import urlquote      # 解决技能数据下载中文名文件为空的问题

from django.template import loader

from .models import Select_Menu
from .models import UserInfo
from .models import Interesting_Menu

from .forms import Lilun_unit_nameForm
from user_verify.forms import CourseForm

from .models import Lilun_title, Lilun_unit_name
from .models import Jineng_title, Jineng_unit_title
from django.db.models.query import QuerySet

from student_study_sys.utils.logger_gf import Logging_gf
from django.conf import settings
logging_path = settings.LOGGING_PATH[0]
logger = Logging_gf(logging_path)

def weihu(request):
    return HttpResponse('<h1 style="color:red;">服务器正在维护，维护截止至2019.03.12晚间</h1>')


# 显示主界面
def show(request):

    content = loader.render_to_string('stu_exam_manage/base.html', context=locals())  # 渲染后网页的内容
    select_menus = Select_Menu.objects.values('menu_name', 'menu_html_id')
    print(select_menus)
    return render(request, 'stu_exam_manage/base.html', locals())  # 返回网页请求内容


# 控制理论题库界面
def question_bank(request):
    lilun_unit_nameform = Lilun_unit_nameForm(request=request)

    return render(request, 'stu_exam_manage/question_bank_base.html', locals())


# 所有理论题目的界面
def question_bank_titles(request):
    post = request.POST
    lilun_unit_name_id = post.get('id', 0)
    if lilun_unit_name_id == '0':
        ''' 排除 ---请选择--- 选项'''
        return HttpResponse(json.dumps(''))
    lilun_unit_titles = Lilun_title.objects.filter(kaoti__id=lilun_unit_name_id).values()  # 根据试卷 id 获取试卷题目
    print(lilun_unit_titles)    # 显示获取到的试卷题目

    # 渲染每一份题目试卷
    content = loader.render_to_string('stu_exam_manage/question_bank_titles.html', context=locals())  # 渲染后网页的内容

    return HttpResponse(json.dumps(content))


# 技能题库
def jineng_bank(request):
    # 120 固定课程为： 机器学习2
    course = '机器学习2'    # 之后修改应该用 id 进行查询
    courseid = request.session.get('courseid', 1)
    all_jineng_titles = Jineng_title.objects.filter(kaoti__course_id=courseid).order_by('kaoti__name', 'kaoti__id')
    all_jineng_titles = sorted(all_jineng_titles, key=lambda jineng_title:int(re.search(r'-unit(\d+)', jineng_title.kaoti.name).group(1)))
    # print(all_jineng_titles)
    return render(request, 'stu_exam_manage/jineng_bank/jineng_bank_base.html', locals())


# 具体每个技能题显示的界面
def jineng_bank_titles(request, jineng_title_id):
    try:
        id = int(jineng_title_id)
        jineng_title = Jineng_title.objects.get(id=id)
        print('jineng_title:', jineng_title)
        return  render(request, 'stu_exam_manage/jineng_bank/jineng_bank_titles.html', locals())
    except Exception as e:
        print(e)    # 110
        return  HttpResponse('请求地址不存在')


# 技能题库--技能数据下载
def download_file(request, file_name):
    print('file_name:', file_name)        # 110
    def file_iterator(the_file_name,chunk_size=512):
        print(the_file_name,'******************')
        with open(the_file_name, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    jineng_title = Jineng_title.objects.filter(codedata_enlabel=file_name)
    if jineng_title:
        file_path = jineng_title[0].codedata
        print('file_path:', file_path)     # 110
        print(settings.MEDIA_ROOT)
        the_file_name = os.path.join(settings.MEDIA_ROOT[:-1], str(file_path))
        logger.info('-------110-测试----' + the_file_name)
        if os.path.exists(the_file_name):
            print(the_file_name,'1111111111111111111111')
            response = StreamingHttpResponse(file_iterator(the_file_name))
            response['Content-Type'] = 'application/octet-stream'
            # 解决技能数据下载中文名文件为空的问题
            file_name_chinese = str(file_path).split('/')[-1]
            print('file_name_chinese:', file_name_chinese)
            # response['Content-Disposition'] = 'attachement;filename="{0}"'.format(urlquote(file_name_chinese))    # windows server 服务器不可用
            from django.utils.encoding import escape_uri_path
            response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name_chinese))
            return response
        else:
            return Http404
    else:
        return Http404


# 错题提交
def error_titles_submit(request):
    status_code = {'code': 200, 'msg': 'success'}
    try:
        post = request.POST
        user_id = int(request.user.id)
        titles = json.loads(post.get('error_titles'))
        titles = [int(i) for i in titles]   # 将id数组元素转为整数
        print(user_id, titles)  # 110 测试
        UserInfo.objects.filter(id=user_id)[0].error_lilun_titles.add(*Lilun_title.objects.filter(id__in=titles))
        print('ok')     # 110 测试
    except Exception as e:
        print(e)
        status_code = {'code': 500, 'msg': '提交检查错误，请查看错题提交模块'}

    return HttpResponse(json.dumps(status_code))


# 错题管理
def error_titles_manage(request):
    get = request.GET   # 通过 get 方法进行请求
    # user_id = request.session.get('id', 1)
    print('request.user:', request.user)
    user_id = request.user.id   # 获取当前用户 id, 路径：student_study_sys\utils\UserVerifyMiddleware.py

    user_all_error_titles = UserInfo.objects.filter(id=user_id)[0].error_lilun_titles.values()
    # print(user_all_error_titles)
    courseid = request.session.get('courseid', 1)
    user_all_error_titles = UserInfo.objects.filter(id=user_id)[0].error_lilun_titles.filter(kaoti__course_id=courseid)
    user_all_error_titles_resource = [(i, i.kaoti) for i in user_all_error_titles]   # 获取题目以及 题目 所对应的 考试试卷
    # print(user_all_error_titles_resource)

    # 图形制表所需参数
    all_unit_titles = Lilun_unit_name.objects.filter(course_id=courseid); print(all_unit_titles) # 指定机器学习1的理论试卷
    all_unit_titles_id = [i.id for i in all_unit_titles]; print(all_unit_titles_id)  # 获取所有理论试卷的 id
    all_unit_titles_name = [i.name for i in all_unit_titles]; print(all_unit_titles_name)    # 获取所有理论试卷的名称 name
    # --通过试卷 id 获取对应的错题数目
    user_error_count = [len(UserInfo.objects.filter(id=user_id)[0].error_lilun_titles.filter(kaoti__id=i)) for i in all_unit_titles_id]; print(user_error_count)

    all_user_error_info = [(user_error_count[index], name) for index,name in enumerate(all_unit_titles_name)]
    # all_unit_titles_name = json.dumps(all_unit_titles_name)
    # user_error_count = json.dumps(user_error_count)

    return render(request,'stu_exam_manage/error_titles_manage.html',locals())


# 信息修改
def info_upd(request):
    status_code = {'code': 201, 'msg': 'error'}
    method = request.method
    if method == 'GET':
        courseform = CourseForm()
        courseid = request.session.get('courseid', 1)
        return render(request, 'stu_exam_manage/info_upd/info_upd_base.html', locals())
    else:
        courseform = CourseForm(request.POST)
        if courseform.is_valid():
            courseData = courseform.cleaned_data
            courseid = courseData.get('name', 1)
            if courseid != '0':
                userid = request.session.get('userid')
                UserInfo.objects.filter(id=userid).update(course_id = courseid)
                request.session['courseid'] = courseid
                print('-----------', UserInfo.objects.filter(id=userid).values())   # 测试
                status_code = {'code': 200, 'msg': 'success'}
                print(status_code)
            else:
                status_code = {'code': 201, 'msg': '该选项不可选择'}
        print(status_code)
        return HttpResponse(json.dumps(status_code))


# 班级公告
def class_notice(request):
    # return HttpResponse('<h1>该功能暂未开放</h1>')
    username = request.session.get('userid', 'xiaofei')
    return render(request, 'stu_exam_manage/class_notice/班级公告.html', locals())


# 好玩的模块
def interesting(request):
    interesting_menus = Interesting_Menu.objects.all()
    return render(request, 'stu_exam_manage/interesting.html', locals())

def interesting_histogram(request):
    ''' 柱状图 '''
    return render(request, 'stu_exam_manage/interesting/histogram.html', locals())

def interesting_tetris(request):
    ''' 俄罗斯方块 '''
    return render(request, 'stu_exam_manage/interesting/tetris.html', locals())

def interesting_calculator(request):
    ''' 科学计算器 '''
    return render(request, 'stu_exam_manage/interesting/calculator.html', locals())

def interesting_five_in_a_row(request):
    ''' 五子棋 '''
    return render(request, 'stu_exam_manage/interesting/five_in_a_row.html', locals())

def interesting_running_man(request):
    ''' 跑跑 '''
    return render(request, 'stu_exam_manage/interesting/running_man.html', locals())

def interesting_mouse_tail(request):
    ''' 鼠标留尾 '''
    return render(request, 'stu_exam_manage/interesting/mouse_tail.html', locals())

def interesting_game2048(request):
    ''' 游戏2048 '''
    return render(request, 'stu_exam_manage/interesting/game2048.html', locals())

def interesting_zhiwujiangshi(request):
    ''' 游戏2048 '''
    return render(request, 'stu_exam_manage/interesting/zhiwujiangshi.html', locals())
